package com.runnor.common.websys.system.security;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.runnor.common.websys.system.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.security.sasl.AuthenticationException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author runnor-yh
 * @date 2023年08月15日 10:54
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
    @Value("${app.security.auth_key}")
    private String authKey;
    @Autowired
    UserServiceImpl userService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwt = request.getHeader("Authorization");
        if (StrUtil.isBlankOrUndefined(jwt)) {
            chain.doFilter(request, response);
            return;
        }

        String userId;
        if (JWTUtil.verify(jwt, authKey.getBytes())) {
            JWT jwtObj = JWTUtil.parseToken(jwt);
            JSONObject payloads = jwtObj.getPayloads();
            userId = (String) payloads.getOrDefault("userid", null);
            request.setAttribute("principal", payloads);
        } else {
            throw new AuthenticationException("token无效");
        }

        // 构建UsernamePasswordAuthenticationToken,这里密码为null，是因为提供了正确的JWT,实现自动登录
        List userAuthority = AuthorityUtils.commaSeparatedStringToAuthorityList(ArrayUtil.join(userService.getUserAuthority(userId).toArray(), ","));
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userId, null, userAuthority);
        token.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(request, response);

    }
}
